package com.ccl.iot;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.ccl.iot.IOTNetAPI;
import com.ccl.iot.IOTNetAPIEnum.ESECURITY_INFO_TYPE;
import com.ccl.iot.publics.Messager;
import com.ccl.iot.publics.Res;
import com.ccl.iot.publics.Window;
import com.ccl.iot.template.ActivityTitled;

import java.util.regex.Pattern;

public class UserInfoActivity extends ActivityTitled {

	private EditText mTvMobile;
	private EditText mTvEmail;
	private EditText mTvQuestion;
	private EditText mTvAnswer;
	private EditText mTvLoginLimit;
	private Button mBtnModify;
	private Button mBtnCancel;
	private LinearLayout mModifyButtons;

	private final int STATE_WATCH = 0;
	private final int STATE_MODIFY = 1;

	private int currentState = STATE_WATCH;
	
	private ScaleAnimation mSa;
	private IOTNetAPI mApi;
	private String mMobile;
	private String mEmial;
	private String mQuestion;
	private String mAnswer;
	private String mLoginLimit;
	private String mPwd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		init();
		initDate();
		initListener();
		modifyState(false);
	}

	private void init() {
		setBackable(true);
		setTitle(R.string.UserInfo);
		setContentView(R.layout.activity_userinfo);

		mModifyButtons = (LinearLayout) findViewById(R.id.ll_modify_userinfo);

		mTvMobile = (EditText) findViewById(R.id.tv_user_mobile);
		
		mTvEmail = (EditText) findViewById(R.id.tv_user_email);
		
		mTvQuestion = (EditText) findViewById(R.id.tv_user_question);
		
		mTvAnswer = (EditText) findViewById(R.id.tv_user_answer);
		
		mTvLoginLimit = (EditText) findViewById(R.id.tv_user_loginlimit);

		mBtnModify = (Button) findViewById(R.id.btn_modify_info);
		mBtnCancel = (Button) findViewById(R.id.btn_cancel_modify);

		mApi = IOTNetAPI.GetInstance();

	}

	
	private void initDate() {
		Intent intent = getIntent();
		//接受传递过来的数据
		mMobile = intent.getStringExtra("mobile");
		mEmial = intent.getStringExtra("emial");
		mQuestion = intent.getStringExtra("question");
		mAnswer = intent.getStringExtra("answer");
		mLoginLimit = intent.getStringExtra("loginLimit");
		mPwd = intent.getStringExtra("pwd");
		
		setAllText();

		//翻转的动画
		mSa = new ScaleAnimation(1, 0, 1, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		mSa.setDuration(100);
		mSa.setRepeatMode(Animation.REVERSE);
		mSa.setRepeatCount(1);

		mSa.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				mBtnModify.setClickable(false);
				mBtnCancel.setClickable(false);
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				//当翻转的动画执行到一半的时候处理UI
				if(currentState == STATE_WATCH){
					mBtnCancel.setVisibility(View.GONE);
					mBtnModify.setText(R.string.ModifyUserInfo);
				}else{
					mBtnModify.setText(R.string.OK);
					mBtnCancel.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				mBtnModify.setClickable(true);
				mBtnCancel.setClickable(true);
			}
		});
	}

	/**
	 * 将数据显示
	 */
	private void setAllText() {
		mTvMobile.setText(mMobile == null ? "" : mMobile);
		mTvEmail.setText(mEmial == null ? "" : mEmial);
		mTvQuestion.setText(mQuestion == null ? "" : mQuestion);
		mTvAnswer.setText(mAnswer == null ? "" : mAnswer);
		mTvLoginLimit.setText(mLoginLimit == null ? "" : mLoginLimit);
	}

	private void initListener() {
		mBtnModify.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				//当当前的状态是查看用户信息时,按下按钮就是要修改用户信息
				if (currentState == STATE_WATCH) {
					modifyState(true);
					
					mModifyButtons.startAnimation(mSa);
					//获取焦点
					mTvMobile.requestFocus();
					//弹出输入法
					Window.ShowInputDialog(getContext());

					//以下是监听这几个EditText的输入框是否有值,当全部都有值时确定修改的按钮才可用
					handleUsefulInfoChange(mTvMobile);
					handleUsefulInfoChange(mTvEmail);
					handleUsefulInfoChange(mTvQuestion);
					handleUsefulInfoChange(mTvAnswer);
					handleUsefulInfoChange(mTvLoginLimit);
				} else {
					//当当前状态是修改用户信息时,按下按钮就是要保存修改用户信息
					modifyInfo();
				}

			}
		});

		mBtnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				modifyState(false);
				setAllText();
				mModifyButtons.startAnimation(mSa);

			}
		});
	}

	/**
	 * 修改状态, 并且设置EditText条目是否可用
	 * @param enable
	 */
	private void modifyState(boolean enable) {
		if (enable) {
			currentState = STATE_MODIFY;
		} else {
			currentState = STATE_WATCH;
		}

		mTvMobile.setEnabled(enable);
		mTvEmail.setEnabled(enable);
		mTvQuestion.setEnabled(enable);
		mTvAnswer.setEnabled(enable);
		mTvLoginLimit.setEnabled(enable);
		
	}
	
	protected void modifyInfo() {

		//修改过后的用户信息
		final String aMobile = mTvMobile.getText().toString().trim();
		final String aEmail = mTvEmail.getText().toString().trim();
		final String aQuestion = mTvQuestion.getText().toString().trim();
		final String aAnswer = mTvAnswer.getText().toString().trim();
		final String aLoginLimit = mTvLoginLimit.getText().toString().trim();

		if (!checkEmail(aEmail)) {
			Messager.Show(Res.GetString(getContext(), R.string.EmailError), 0);
			return;
		}

		if (!checkMobile(aMobile)) {
			Messager.Show(Res.GetString(getContext(), R.string.MobileError), 0);
			return;
		}

		//验证码的对话框
		AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

		View view = View.inflate(getContext(), R.layout.view_get_safecode, null);

		final EditText etInput = (EditText) view.findViewById(R.id.view_et_input_code);
		final Button btnGetCode = (Button) view.findViewById(R.id.view_btn_getcode);
		Button btnCancel = (Button) view.findViewById(R.id.view_btn_input_cancel);
		final Button btnConfirm = (Button) view.findViewById(R.id.view_btn_input_confirm);
		
		builder.setView(view);
		final AlertDialog dialog = builder.create();
		
		btnGetCode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				btnGetCode.setEnabled(false);
				CountDownTimer timer = new CountDownTimer(60000, 1000) {

					@Override
					public void onTick(long millisUntilFinished) {
						btnGetCode.setText(millisUntilFinished / 1000 + "");
					}

					@Override
					public void onFinish() {
						btnGetCode.setEnabled(true);
						btnGetCode.setText(R.string.RegetSecurityCode);
					}
				};
				//获取验证码的按钮按下之后开始倒计时
				timer.start();

				//获取验证码
				if (mApi.getSecurityCode((short) 2052, ESECURITY_INFO_TYPE.ESECURITY_INFO_TYPE_EMAIL, mEmial)) {
					Messager.Show(Res.GetString(getContext(), R.string.SecurityCodePrompt), 0);
				}
			}
		});

		etInput.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				//只有当EditText输入框中有值按钮才可用
				btnConfirm.setEnabled(!TextUtils.isEmpty(etInput.getText().toString().trim()));
			}
		});

		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		btnConfirm.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//修改用户信息
				if(mApi.changeUserInfo(mApi.getLogonUserName(), mPwd, aMobile, 
						aEmail, aQuestion, aAnswer, 
						Long.parseLong(aLoginLimit), Integer.parseInt(etInput.getText().toString().trim()))){
					//当修改成功要重新赋值
					mMobile = aMobile;
					mEmial = aEmail;
					mQuestion = aQuestion;
					mAnswer = aAnswer;
					mLoginLimit = aLoginLimit;
					Messager.Show(Res.GetString(getContext(), R.string.ModifyInfoSuccess), 0);
					dialog.dismiss();
					
					modifyState(false);
					setAllText();
					mModifyButtons.startAnimation(mSa);
				}else{
					//修改失败
					Messager.Show(Res.GetString(getContext(), R.string.ModifyInfoError), 0);
				} 
			}
		});
		
		//设置是否可以点击外部消失
		dialog.setCancelable(false);

		dialog.show();

	}

	private void handleUsefulInfoChange(EditText aInfo) {
		if (aInfo != null) {
			aInfo.addTextChangedListener(new TextWatcher() {
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				}

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
				}

				@Override
				public void afterTextChanged(Editable s) {
					mBtnModify.setEnabled(isInfoValid());
				}
			});
		}
	}

	private boolean isInfoValid() {
		return !TextUtils.isEmpty(getEditTextString(mTvMobile)) && !TextUtils.isEmpty(getEditTextString(mTvEmail)) && !TextUtils.isEmpty(getEditTextString(mTvQuestion))
				&& !TextUtils.isEmpty(getEditTextString(mTvAnswer)) && !TextUtils.isEmpty(getEditTextString(mTvLoginLimit));
	}

	private String getEditTextString(EditText et) {
		return et.getText().toString().trim();
	}

	/**
	 * 正则表达式检索邮箱格式是否正确
	 * @param email
	 * @return
	 */
	private boolean checkEmail(String email) {
		String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		return Pattern.matches(check, email);
	}

	/**
	 * 正则表达式检索手机号码格式是否正确
	 * @param mobile
	 * @return
	 */
	private boolean checkMobile(String mobile) {
		String REGEX_MOBILE = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
		return Pattern.matches(REGEX_MOBILE, mobile);
	}

}
